package com.touzbi.hss.bo;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.touzbi.hss.beans.Patient;
import com.touzbi.hss.dao.AbstractDAOFactory;
import com.touzbi.hss.dao.AbstractPatientDAO;
import com.touzbi.hss.parametermanager.AbstractParameterManager;
import com.touzbi.hss.parametermanager.HttpParameterManager;
import com.touzbi.hss.validator.AbstractValidator;
import com.touzbi.hss.validator.Validator;
import com.touzbi.hss.validator.ValidatorException;

public class FormBO {

	private static final String FIRST_NAME_PARAM = "firstName";
	private static final String LAST_NAME_PARAM = "lastName";
	private static final String MAIL_PARAM = "mail";
	private static final String PHONE_NUMBER_PARAM = "phoneNumber";

	private static final String SUCCESS_MSG = "Patient successfully created";

	private AbstractPatientDAO patientDAO;
	private AbstractParameterManager paramManager;
	private Map<String, String> error = new HashMap<String, String>();
	private String successMsg = "";

	public FormBO(AbstractDAOFactory daoFactory, HttpServletRequest req) {
		this.patientDAO = daoFactory.getPatientDAO();
		this.paramManager = new HttpParameterManager(req);
	}

	private Patient getPatient(HttpServletRequest req) {
		Patient patient = new Patient();
		AbstractValidator validator = new Validator();
		try {
			patient.setFirstName(validator.getValidFirstName(this.paramManager
					.getParamValue(FIRST_NAME_PARAM)));
		} catch (ValidatorException e) {
			this.error.put(FIRST_NAME_PARAM, e.getMessage());
		}
		try {
			patient.setLastName(validator.getValidLastName(this.paramManager
					.getParamValue(LAST_NAME_PARAM)));
		} catch (ValidatorException e) {
			this.error.put(LAST_NAME_PARAM, e.getMessage());
		}
		try {
			patient.setMail(validator.getValidMail(this.paramManager
					.getParamValue(MAIL_PARAM)));
		} catch (ValidatorException e) {
			this.error.put(MAIL_PARAM, e.getMessage());
		}
		try {
			patient.setPhoneNumber(validator
					.getValidPhoneNumber(this.paramManager
							.getParamValue(PHONE_NUMBER_PARAM)));
		} catch (ValidatorException e) {
			this.error.put(PHONE_NUMBER_PARAM, e.getMessage());
		}
		return patient;
	}

	public Patient addPatient(HttpServletRequest req) {
		Patient patient = getPatient(req);
		if (this.error.isEmpty()) {
			this.patientDAO.addPatient(patient);
			this.successMsg = SUCCESS_MSG;
		}
		return patient;
	}

	public boolean registrationSuccessfull() {
		return !this.successMsg.isEmpty() && this.successMsg != null;
	}

	public String getSuccessMsg() {
		return successMsg;
	}

	public Map<String, String> getError() {
		return this.error;
	}
}
